package com.itboye.lottery.activity.user;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.bylibrary.util.ScreenUtil;
import com.itboye.bylibrary.widget.glide.GlideUtil;
import com.itboye.lottery.R;
import com.itboye.lottery.activity.daletou.BascketballMainActivity;
import com.itboye.lottery.activity.daletou.DaLeTouMainActivity;
import com.itboye.lottery.activity.football.FootballMainActivity;
import com.itboye.lottery.activity.shuangseqiu.ShuangSeQiuMainActivity;
import com.itboye.lottery.adapter.BetDetailListAdapter;
import com.itboye.lottery.adapter.NumberBetDetailListAdapter;
import com.itboye.lottery.alert.ByAlert;
import com.itboye.lottery.base.BaseActivity;
import com.itboye.lottery.bean.BetDetailBean;
import com.itboye.lottery.bean.BetZqDetailBean;
import com.itboye.lottery.presenter.UserPresenter;
import com.itboye.lottery.retrofit.ResponseCallback;
import com.itboye.lottery.utils.Const;
import com.itboye.lottery.view.FlowLayout;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import static com.itboye.bylibrary.util.TimeUtils.getFormatTime;

public class TouzhuDetailActivity extends BaseActivity implements ResponseCallback {

    String id;
    UserPresenter userPresenter;
    private BetZqDetailBean betZqDetailBean;
    ImageView iv_icon;
    TextView tv_title;
    TextView tv_num;//期数
    TextView touzhu_detial_tv_status;//出票状态
    TextView tv_bet_detail_open_time;//出奖时间
    TextView tv_bet_detail_touzhu_type;//投注方式
    TextView tv_bet_detail_guoguan_type;//过关方式
    TextView tv_betdetail_add_time;//投注时间
    TextView tv_bet_sn;//投注编号
    TextView tv_betdetail_money;//投注金额
    private int cid; // 彩种类型  0数字彩  1 足球彩 2篮球彩
    private String gamecate;// //彩票种类2001 大乐透 1001 双色球 3010 足球  3001篮球
    RecyclerView rv_zq_bet_match;
    private int splitWidth;
    private BetDetailBean betNumDetailBean;

    LinearLayout ll_kaijiang_code,ll_touzhu_code;
    FlowLayout fl_kaijiang_red_code,fl_kaijiang_blue_code;
    LinearLayout ll_bet_record_detail;
    TextView tv_bet_jiajiang;
    private BetDetailListAdapter adapter;
    RecyclerView rv_numberbet;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_touzhu_detail;
    }

    @Override
    protected void initData() {
        id = getIntent().getStringExtra("id");
        cid = getIntent().getIntExtra("cid", 0);// 彩种类型  0数字彩  1 足球彩 2篮球彩
        gamecate = getIntent().getStringExtra("gamecate");// //彩票种类2001 大乐透 1001 双色球 3010 足球  3001篮球
        userPresenter = new UserPresenter(this);
        getTouZhuDetail();
    }

    TextView textView1;

    @SuppressLint("SetTextI18n")
    private void setBetZqDetailData() {
        tv_num.setText("第" + betZqDetailBean.getInfo().getNumber() + "期");
        tv_title.setText(betZqDetailBean.getInfo().getName());
        GlideUtil.display(this, betZqDetailBean.getInfo().getPic(), iv_icon);
//        touzhu_detial_tv_status.setText(Html.fromHtml(getStatus(Integer.parseInt(betZqDetailBean.getInfo().getIs_prize()))));
        if (betZqDetailBean.getInfo().getIs_prize().equals("1")) {
            touzhu_detial_tv_status.setText(Html.fromHtml("<font color='red'>已中奖！" + betZqDetailBean.getInfo().getPrize_money() + "元"));
        } else {
            touzhu_detial_tv_status.setText(Html.fromHtml(betZqDetailBean.getInfo().getStatus()));
        }
        tv_bet_detail_open_time.setText("开奖时间：预计" + betZqDetailBean.getInfo().getDate() + " " + betZqDetailBean.getInfo().getTime() + "开奖");//开奖时间
        tv_betdetail_add_time.setText("投注时间：" + getFormatTime(betZqDetailBean.getInfo().getAdd_time() * 1000, "yyyy-MM-dd HH:mm"));//投注时间
        tv_bet_sn.setText("投注编号：" + betZqDetailBean.getInfo().getSn());//投注编号
        tv_betdetail_money.setText("投注金额：" + betZqDetailBean.getInfo().getAmount() + "元");
        tv_bet_detail_touzhu_type.setText("投注方式：" + betZqDetailBean.getInfo().getBet_num() + "注 " + betZqDetailBean.getInfo().getMultiple() + "倍");
        tv_bet_jiajiang.setText(Html.fromHtml("加奖：<font color='red'>" + betZqDetailBean.getInfo().getBonus() + "元</font>"));
        StringBuffer playGames = new StringBuffer();
        for (String s : betZqDetailBean.getInfo().getPlay_game()) {
            if (s.equals("1")) {
                playGames.append("单关,");
            } else {
                playGames.append(s + "串1,");
            }
        }
        try {
            tv_bet_detail_guoguan_type.setText("过关方式：" + playGames.toString().substring(0, playGames.toString().length() - 1));
        } catch (Exception e) {

        }
        List<BetZqDetailBean.NoteRecordEntity> list = betZqDetailBean.getNote_record();

        splitWidth = ScreenUtil.dpToPx(this, 0.5f);
        int height = ScreenUtil.dpToPx(this, 120);
        int width = ScreenUtil.getScreenWidth(this);
        int vWidth = width / 3;
//        rv_zq_bet_match.removeAllViews();
        rv_zq_bet_match.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BetDetailListAdapter(this, list);
        adapter.setOriginNum(betZqDetailBean.getInfo().getOrigin_num());
        adapter.setType(betZqDetailBean.getInfo().getType());
        rv_zq_bet_match.setAdapter(adapter);
        View headerView = View.inflate(this, R.layout.header_bet_record_detail, null);
        textView1 = headerView.findViewById(R.id.textView1);
        if (betZqDetailBean.getInfo().getType().equals("2")) {
            textView1.setText("客队VS主队");
        } else {
            textView1.setText("主队VS客队");
        }
        ll_bet_record_detail.addView(headerView, 0);
        ////////////////////////////////////////足球赛事
//        addBetMatch(list, vWidth, height, 3);
    }

    private void addBetMatch(List<BetZqDetailBean.NoteRecordEntity> list, int width, int height, int maxLine) {
        int index = 0;
        //因为我从0的时候就+height 所有初始化的时候-height 就刚刚好是0
        int wm = 0;
        int hm = -splitWidth;
        int topMargin = -height;
        int leftMargin = ((maxLine - 1) * splitWidth) / 2;
        boolean br = false;
        for (int i = 0; i < list.size(); i++) {
            BetZqDetailBean.NoteRecordEntity infoEntity = list.get(i);
            for (int i1 = 0; i1 < 3; i1++) {
                leftMargin += width;
                wm += ScreenUtil.dpToPx(this, 0.5f);
                if (index % maxLine == 0) {
                    wm = 0;
                    //这里初始化 ((maxLine - 1) * splitWidth) / 2 是由于两个格子都有边框 所有并排在一起的地方会很粗
                    //我就将后一个的位置的边线与前一个重叠 然后重叠出来的空间 分配给整个容器左右两边当间距
                    leftMargin = ((maxLine - 1) * splitWidth) / 2;
                    topMargin += height;
                    hm += splitWidth;
                    index = 0;
                }
                String str = "";
                String[] content;
//                if (betZqDetailBean.getInfo().getType().equals("2")) {
//                    content = getLqBetContentAndPrizeContent(betZqDetailBean.getInfo().getOrigin_num(), infoEntity);
//                } else {
//                    content = getBetContentAndPrizeContent(, infoEntity);
//                }
//                if (content == null) {
//                    continue;
//                }
//                switch (i1) {
//                    case 0:
//                        str = infoEntity.getQiudui().getNum() + "<br />" + infoEntity.getQiudui().getH_cn() + " VS " + infoEntity.getQiudui().getA_cn();
//                        break;
//                    case 1:
//                        str = content[1];
//                        break;
//                    case 2:
//                        str = content[0];
//                        break;
//                }
                rv_zq_bet_match.addView(createTextView(width, height, leftMargin > 0 ? leftMargin - wm : leftMargin,
                        topMargin > 0 ? topMargin - hm : topMargin, str));
                index++;
            }

        }
    }


    private TextView createTextView(int width, int height, int leftMargin, int topMargin, String str) {
        TextView cb = new TextView(this);
        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(width, RelativeLayout.LayoutParams.WRAP_CONTENT);
        rl.leftMargin = leftMargin;
        rl.topMargin = topMargin;
//        rl.addRule(RelativeLayout.CENTER_VERTICAL);

        cb.setLayoutParams(rl);
        cb.setTextColor(ContextCompat.getColorStateList(this, R.color.black_white_selector));
        cb.setGravity(Gravity.CENTER);
//        cb.setBackgroundResource(R.drawable.red_white_selecter);
        cb.setText(Html.fromHtml(str));
//        cb.setText(StringUtils.matcherSearchText(color, text, keyword));
        return cb;
    }


    private void getTouZhuDetail() {
        switch (cid) {
            case 0:
                userPresenter.betShuZiCaiDetail(id);
                break;
            case 1:
            case 2:
                userPresenter.betZqCaiDetail(id);
                break;
        }
    }

    private String getStatus(int status) {
        //	-1:已过期：0：未出票，1：出票中，2：出票成功，3：出票失败
        String statusValue = "";
        switch (status) {
            case -1:
                statusValue = "已过期";
                break;
            case 0:
                statusValue = "未出票";
                break;
            case 1:
                statusValue = "出票中";
                break;
            case 2:
                statusValue = "出票成功";
                break;
            case 3:
                statusValue = "出票失败";
                break;
            case 4:
                break;
//            case 0:
//                statusValue = "未开奖";
//                break;
//            case 1:
//                statusValue = "<font color='red'>已中奖！" + betZqDetailBean.getInfo().getPrize_money() + "元</font>";
//                break;
//            case 2:
//                statusValue = "未中奖";
//                break;
        }
        return statusValue;
    }

    @Override
    public void onClick(View view) {

    }

    public void youji(View view) {
        startActivity(new Intent(this, AddressListActivity.class));
    }

    public void touzhu(View view) {
        switch (gamecate) {
            case "1001":
                if (!Const.Companion.getShuangseqiu()) {
                    ByAlert.alert("投注已关闭");
                    return;
                }
                startActivity(new Intent(this, ShuangSeQiuMainActivity.class));
                break;
            case "2001":
                if (!Const.Companion.getDaletou()) {
                    ByAlert.alert("投注已关闭");
                    return;
                }
                startActivity(new Intent(this, DaLeTouMainActivity.class));
                break;
            case "3010":
            case "0":
                if (!Const.Companion.getZq()) {
                    ByAlert.alert("投注已关闭");
                    return;
                }
                startActivity(new Intent(this, FootballMainActivity.class));
                break;
            case "3001":
                if (!Const.Companion.getLq()) {
                    ByAlert.alert("投注已关闭");
                    return;
                }
                startActivity(new Intent(this, BascketballMainActivity.class));
                break;
        }
        finish();
    }

    @Override
    public void success(@NotNull Object o, @NotNull String requestSuccessType) {
        if (requestSuccessType == userPresenter.betShuZiCaiDetail_SUCCESS) {
            betNumDetailBean = (BetDetailBean) o;
            tv_bet_detail_guoguan_type.setVisibility(View.GONE);
            ll_touzhu_code.setVisibility(View.VISIBLE);
            setBetNumDetailData();
        }
        if (requestSuccessType == userPresenter.betZqCaiDetail_SUCCESS) {
            tv_bet_detail_guoguan_type.setVisibility(View.VISIBLE);
            ll_touzhu_code.setVisibility(View.GONE);
            betZqDetailBean = (BetZqDetailBean) o;
            setBetZqDetailData();
        }
    }

    @SuppressLint("SetTextI18n")
    private void setBetNumDetailData() {
        tv_num.setText("第" + betNumDetailBean.getInfo().getNumber() + "期");
        tv_title.setText(betNumDetailBean.getInfo().getName());// 标题
        GlideUtil.display(this, betNumDetailBean.getInfo().getPic(), iv_icon);
        touzhu_detial_tv_status.setText(getStatus(Integer.parseInt(betNumDetailBean.getInfo().getStatus())));//订单状态
        tv_bet_detail_open_time.setText("开奖时间：预计" + betNumDetailBean.getInfo().getStart_time() + "开奖");//开奖时间
        tv_betdetail_add_time.setText("投注时间：" + getFormatTime(betNumDetailBean.getInfo().getAdd_time() * 1000, "MM-dd HH:mm"));//投注时间
        tv_bet_sn.setText("投注编号：" + betNumDetailBean.getInfo().getSn());//投注编号
        tv_betdetail_money.setText("投注金额：" + betNumDetailBean.getInfo().getAmount() + "元");
//        tv_bet_detail_touzhu_type.setText("投注方式：" + betBean.getPlaytype() + " " + betNumDetailBean.getInfo().getBet_num() + "注 " + betNumDetailBean.getInfo().getMultiple() + "倍");
        tv_bet_detail_touzhu_type.setText("投注方式：" + betNumDetailBean.getInfo().getBet_num() + "注 " + betNumDetailBean.getInfo().getMultiple() + "倍");
        //投注号码
        rv_numberbet.setLayoutManager(new LinearLayoutManager(this));
        NumberBetDetailListAdapter adapter=new NumberBetDetailListAdapter(this, betNumDetailBean.getBet());
        rv_numberbet.setAdapter(adapter);
        rv_numberbet.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        //开奖code显示
        if (betNumDetailBean.getInfo().getIs_prize().equals("0")) {
            //已开奖
            ll_kaijiang_code.setVisibility(View.GONE);
        }else{
            ll_kaijiang_code.setVisibility(View.VISIBLE);
            if (betNumDetailBean.getInfo().getWill()!=null) {
                if (betNumDetailBean.getInfo().getWill().size()>0) {
                    adapter.addNumberViews(betNumDetailBean.getInfo().getWill().get(0).toArray(new String[betNumDetailBean.getInfo().getWill().get(0).size()]),fl_kaijiang_red_code,true);
                }
                if (betNumDetailBean.getInfo().getWill().size()>1) {
                    adapter.addNumberViews(betNumDetailBean.getInfo().getWill().get(1).toArray(new String[betNumDetailBean.getInfo().getWill().get(1).size()]),fl_kaijiang_blue_code,false);
                }
            }
        }
    }

    @Override
    public void fail(int code, @NotNull Object msg, @NotNull String requestErrorType) {
        ByAlert.alert(msg);
    }
}
